//
//  WBFristPagePictureView.swift
//  weibo
//
//  Created by  郭航 on 16/6/30.
//  Copyright © 2016年 郭航. All rights reserved.
//

import UIKit

private let cellID = "cellID"

private let cellMar: CGFloat = 5
private let cellW: CGFloat = (SCREENW - 2*cellMargin - 2*cellMar) / 3
private let cellH = cellW

class WBFristPagePictureView: UICollectionView {
    
    var dataModel: [WBFristPagePictureModel]? {
        didSet {
            countLabel.text = "\(dataModel?.count ?? 0)"
            
            self.snp_updateConstraints { (make) in
                make.size.equalTo(getViewSize())
            }
            
            reloadData()
        }
    }
    
    private lazy var countLabel: UILabel = UILabel(textColor: UIColor.redColor(), textAlignment: .Center, font: 35)

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        backgroundColor = UIColor.clearColor()
        
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
        self.snp_makeConstraints { (make) in
            make.width.equalTo(0)
            make.height.equalTo(0)
        }
        
        dataSource = self
        delegate = self
        
        registerClass(WBFristPagePictureCell.self, forCellWithReuseIdentifier: cellID)
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: cellW, height: cellH)
        layout.minimumInteritemSpacing = cellMar
        layout.minimumLineSpacing = cellMar
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func getViewSize() -> CGSize {
        let count = dataModel?.count ?? 0
        
        /// 列数
        let col: Int = count == 4 ? 2 : (count < 3 ? count : 3)
        /// 行数
        let row: Int = ((count - 1) / 3) + 1
        
        let width: CGFloat = CGFloat(col) * cellW + CGFloat(col - 1) * cellMar
        let height: CGFloat = CGFloat(row) * cellH + CGFloat(row - 1) * cellMar
        
        return CGSize(width: width, height: height)
    }
    
}

extension WBFristPagePictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataModel?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! WBFristPagePictureCell
        
        cell.dataModel = dataModel![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let photoBrowser = SDPhotoBrowser()
        
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = dataModel?.count ?? 0
        photoBrowser.sourceImagesContainerView = self
        
        photoBrowser.show()
    }
    
}

extension WBFristPagePictureView: SDPhotoBrowserDelegate {
    
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! WBFristPagePictureCell
        return cell.imageView.image
    }
    
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let URLStr = ((dataModel![index].thumbnail_pic ?? "") as NSString).stringByReplacingOccurrencesOfRegex("thumbnail", withString: "bmiddle") as String
        return NSURL(string: URLStr)
    }
    
}


class WBFristPagePictureCell: UICollectionViewCell {
    
    var dataModel: WBFristPagePictureModel? {
        didSet {
            imageView.sd_setImageWithURL(NSURL(string: dataModel?.thumbnail_pic ?? ""), placeholderImage: UIImage(named: "timeline_card_top_background"))
        }
    }
    
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
